import json
import os
import requests

from common import errors

test_url = 'https://oapi.dingtalk.com/robot/send?access_token=fb8413e4c199cc5d80092cc17c4363b4615bb4e8476d27b38d1aeb651e3bd3e2'


def get_dingding_url():
    config_name = os.getenv('FLASK_ENV') or 'default'
    if config_name == 'default':
        url = test_url
    elif config_name == 'production':
        url = test_url
    else:
        url = test_url
    return url


# 发送到钉钉群
def send_msg_to_dingding(content, url, at_mobiles=None):
    headers = {
        "Content-Type": "application/json",
    }
    payload = {
        "msgtype": "text",
        "text": {
            "content": '[项目管理平台][消息通知]\n{}'.format(content)
        },
    }
    if at_mobiles and len(at_mobiles) != 0:
        payload['at'] = {
            'atMobiles': at_mobiles
        }

    res = requests.post(url=url, data=json.dumps(payload), headers=headers)
    # 这里返回的是一个json字符串，所以转换成json格式，注意json后面带括号
    res_json = res.json()

    if res_json['errmsg'] != 'ok':
        raise errors.BadRequestError("钉钉消息发送失败，错误码：{}".format(res_json['errcode']))
